<template>
  <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="100px">
    <el-row>
      <el-col>
        <el-form-item size="mini" label="材料组名称" prop="Name">
          <el-input v-model="dataForm.Name" :disabled="read" maxlength="25" show-word-limit placeholder="请输入材料组名称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item size="mini" label="材料组代码" prop="Code">
          <el-input v-model="dataForm.Code" :disabled="read" maxlength="25" show-word-limit placeholder="请输入材料组代码" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item size="mini" label="上级材料组">
          <el-popover
            ref="positionListPopover"
            v-model="parentVisible"
            :width="parentWidth"
            placement="bottom-start"
            trigger="click"
            :disabled="read"
            @show="getPopover('parentName','positionListPopover')"
          >
            <div style="height: 200px;overflow-y:auto">
              <el-tree
                ref="positionListTree"
                :data="positionList"
                :props="positionListTreeProps"
                node-key="Id"
                :default-expand-all="false"
                :highlight-current="true"
                :expand-on-click-node="false"
                @current-change="positionListTreeCurrentChangeHandle"
              />
            </div>
          </el-popover>
          <el-input ref="parentName" v-model="dataForm.ParentName" v-popover:positionListPopover :readonly="true" placeholder="点击选择上级职位" class="menu-list__input" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item size="mini" label="所属租户" prop="Tenant">
          <el-select
            v-model="dataForm.Tenant"
            :disabled="read"
            default-first-option
            filterable
            remote
            reserve-keyword
            style="width: 100%"
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in options"
              :key="item.Code"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row v-if="!read">
      <el-col style="text-align: right;">
        <el-button size="mini" icon="el-icon-close" @click="visible = false">取消</el-button>
        <el-button size="mini" icon="el-icon-check" type="primary" @click="dataFormSubmit()">提交</el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import { treeDataTranslate } from '@/utils'
import { fetchAll } from '@/api/tenant'
import { fetchMategroup, saveMategroup, updateMategroup, getMategroup } from '@/api/mategroup'
export default {
  props: [
    // eslint-disable-next-line vue/require-prop-types
    'id'
  ],
  data() {
    return {
      tenantList: [],
      options: [],
      loading: false,
      positionList: [],
      parentVisible: false,
      parentWidth: 0,
      read: false,
      positionListTreeProps: {
        label: 'Name',
        children: 'children'
      },
      dataForm: {
        Id: '',
        Code: '',
        Name: '',
        ParentName: '',
        ParentId: '',
        Tenant: ''

      },
      dataRule: {
        Name: [
          { required: true, message: '物料组名称不能为空', trigger: 'blur' }
        ],
        Code: [
          { required: true, message: '物料组代码不能为空', trigger: 'blur' }
        ],
        Tenant: [{
          required: true, message: '所属租户不能为空', trigger: 'blur'
        }]
      }
    }
  },
  mounted() {
    if (this.id > 0) {
      this.init(this.id)
    }
  },
  methods: {
    getPopover(container, popover) {
      if (this.read) {
        this.parentVisible = true
      }
      this.parentWidth = this.$refs[container].$el.offsetWidth
      this.parentVisible = true
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.tenantList.filter(item => {
            return item.Name.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
              item.Code.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200
        )
      } else {
        this.options = this.tenantList
      }
    },
    // 菜单树选中
    positionListTreeCurrentChangeHandle(data, node) {
      this.dataForm.ParentId = data.Id
      this.dataForm.ParentName = data.Name
      this.parentVisible = false
    },
    // 菜单树设置当前选中节点
    positionListTreeSetCurrentNode() {
      this.$nextTick(() => {
        if (this.$refs.positionListTree) {
          this.$refs.positionListTree.setCurrentKey(this.dataForm.ParentId)
        }
      })

      // this.dataForm.ParentName = (this.$refs.positionListTree.getCurrentNode() || {})['Name']
    },
    init(id, parentId, tenant) {
      if (this.id > 0) {
        this.read = true
      } else {
        this.read = false
      }
      this.dataForm.Id = id || 0
      this.dataForm.ParentName = ''
      this.dataForm.Parentid = -1
      this.dataForm.Tenant = ''
      // 获取租户
      fetchAll().then((data) => {
        if (data && data.code === '20000') {
          const result = data.data
          this.tenantList = result
          this.options = this.tenantList
          // this.$refs['dataForm'].resetFields()
          this.dataForm.Tenant = tenant
        }
      }).then(() => {
        fetchMategroup().then(({ data }) => {
          this.positionList = treeDataTranslate(data, 'Id', 'Parentid')
          // console.log(this.positionList)
          this.dataForm.ParentId = parentId || -1
          this.dataForm.Id = id || 0
          const r = data.filter(r => r.Id === parentId)
          if (r && r.length > 0) {
            this.dataForm.ParentName = r[0].Name
          }
          this.positionListTreeSetCurrentNode()
          this.dataForm.Tenant = tenant
        })
      }).then(() => {
        if (id && id > 0) {
          getMategroup(id).then((data) => {
            if (data && data.code === '20000') {
              this.dataForm.Id = data.mategroup.Id
              this.dataForm.Code = data.mategroup.Code
              this.dataForm.Name = data.mategroup.Name
              this.dataForm.Tenant = data.mategroup.Tenant
              this.dataForm.ParentId = data.mategroup.Parentid
              const k = this.positionList.filter(r => r.Id === this.dataForm.ParentId)
              if (k && k.length > 0) {
                this.dataForm.ParentName = k[0].Name
              }
              this.positionListTreeSetCurrentNode()
            }
          })
        }
      })
    },
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var data = {
            'Id': this.dataForm.Id || undefined,
            'Code': this.dataForm.Code,
            'Name': this.dataForm.Name,
            'ParentId': this.dataForm.ParentId || -1,
            'Tenant': this.dataForm.Tenant
          }
          var permission
          if (this.dataForm.Id && this.dataForm.Id > 0) {
            permission = updateMategroup(data)
          } else {
            permission = saveMategroup(data)
          }
          permission.then((data) => {
            if (data && data.code === '20000') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.$emit('close')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
